package cn.pdx.elec.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

/**
 * 出来验证码和记住我的类
 * @author Administrator
 *
 */
public class LoginUtils {

	
	/**
	 * @Name:checkNumber
	 * @Description:验证验证码
	 * @author 彭定旭
	 * @Create Date:2013-4-24
	 * @return 无
	 */
	public static boolean checkNumber(HttpServletRequest request) {
		
		//从session中获取验证码
		HttpSession session=request.getSession(false);
		if(session==null)
		{
			return false;
		}
		String check_number_key=(String) session.getAttribute("CHECK_NUMBER_KEY");
		
		//为空的话
		if(StringUtils.isBlank(check_number_key))
		{
			return false;
		}
		//从登录页面获取验证码的数值
		String checkNumber=request.getParameter("checkNumber");
		if(StringUtils.isBlank(checkNumber))
		{
			
			return false;
		}
		
		return check_number_key.equalsIgnoreCase(checkNumber);
	}

	 /**
	 * @Name:remeberMeByCookie
	 * @Description:添加记住我功能,cookie
	 * @author 彭定旭
	 * @version：v1.00（版本号）
	 * @Create Date:2013-4-24(创建日期)
	 * @parameters:HttpServletRequest request,HttpServletResponse response
	 *             因为要获取页面登录用户名和密码,所以要request,又要返回所以用response
	 * @return:无
	 * @throws UnsupportedEncodingException 
	 */
	public static void remeberMeByCookie(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {

		//获取页面登录用户名和密码
		String name=request.getParameter("name");
		String password=request.getParameter("password");
		
		//创建2个Cookie,分别用来存放登录名和密码
		//处理Cookie中存在的中文字符问题
		String codeName=URLEncoder.encode(name, "UTF-8");
		Cookie nameCookie=new Cookie("name", codeName);
		Cookie passwordCookie=new Cookie("password", password);
		
		//设置Cookie的有效路径
		//System.out.println("path="+request.getContextPath());
		nameCookie.setPath(request.getContextPath()+"/");
		passwordCookie.setPath(request.getContextPath()+"/");
		/**
		 * 从页面中获取记住我的复选框的值
		 * 如果有值,设置Cookie的有效时长
		 * 如果没有值,情况Cookie的有效时长
		 * <input type="checkbox" name="remeberMe"  id="remeberMe" value="yes"  >
		 */
		String remeberMe=request.getParameter("remeberMe");
		
		if(remeberMe!=null && remeberMe.equals("yes"))
		{
         //设置Cookie有效时长,一周
			nameCookie.setMaxAge(7*24*60*60);
			passwordCookie.setMaxAge(7*24*60*60);
		}
		else{
			
			//清空Cookie有效时长
			nameCookie.setMaxAge(0);
			passwordCookie.setMaxAge(0);
		}
		//将两个对象存在cookie中
		response.addCookie(nameCookie);
		response.addCookie(passwordCookie);
	}

	
}
